import React, { useState } from "react";
import { Input, Button, Notify } from "react-vant";

const Index: React.FC = () => {
  const [showCode, setShowCode] = useState(true);
  const [tel, setTel] = useState("13111111111");
  const [code, setCode] = useState("");
  const [downTime, setDownTime] = useState(10);
  const getCode = () => {
    // 验证手机号
    if (!/^1[3-9]\d{9}$/.test(tel)) {
      Notify.show({ type: "danger", message: "手机号格式不正确" });
      return;
    }
    // 获取验证啊
    setCode(Math.random().toString().slice(2, 6));

    // 倒计时
    startDownTime();

    // 切换庄涛
    setShowCode(false);
  };

  const startDownTime = () => {
    const timer = setInterval(() => {
      // hooks 更新在定时器的时候， 需要格外注意异步更新问题
      // 如果想要从上一次获取到结果， 必须使用回调函数形式， 不可以使用值的方式
      setDownTime((state) => {
        if (state === 1) {
          clearInterval(timer);
          return 10;
        }
        return state - 1;
      });
    }, 1000);
  };
  return (
    <div className="login">
      <div>{downTime}</div>
      {showCode ? (
        <Input
          placeholder="请输入手机号"
          style={{ border: "1px solid #ccc", height: 44, marginBottom: 10 }}
          value={tel}
          onChange={(value) => setTel(value)}
        ></Input>
      ) : (
        <Input
          placeholder="请输入验证码"
          style={{ border: "1px solid #ccc", height: 44, marginBottom: 10 }}
          value={code}
          onChange={(value) => setCode(value)}
        ></Input>
      )}

      <Button
        disabled={downTime !== 10}
        type="primary"
        block
        onClick={() => getCode()}
      >
        {downTime === 10 ? "获取验证码" : "还剩" + downTime + "秒"}
      </Button>
    </div>
  );
};

export default Index;
